package com.skt.controller;

import com.skt.domain.DTO.request.AddToCartRequest;
import com.skt.domain.VO.CartVO;
import com.skt.exception.BusinessException;
import com.skt.service.CartService;
import com.skt.utils.LogUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/cart")
@RequiredArgsConstructor
@Tag(name = "购物车接口")
public class CartController {

    private final CartService cartService;

    @Operation(
            summary = "获取购物车",
            description = "获取当前用户的购物车信息。如果购物车不存在，会自动创建新的购物车后返回。支持获取现有购物车和自动创建两种功能。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功，返回购物车信息（包含自动创建功能）"),
            @ApiResponse(responseCode = "401", description = "未授权访问")
    })
    @GetMapping
    public ResponseEntity<CartVO> getCart() {
        // 设置追踪ID
        LogUtil.setTraceId();

        // 开始性能监控
        LogUtil.startTimer("GET_CART");
        log.info("获取购物车请求");
        try {
            CartVO cartVO = cartService.createOrGetCart();
            if (cartVO.getCartId() == null) {
                log.info("自动创建购物车成功: cartId={}, userId={}, itemCount={}",
                        cartVO.getCartId(), cartVO.getUserId(), cartVO.getItems().size());
            } else {
                log.info("获取现有购物车成功: cartId={}, userId={}, itemCount={}",
                        cartVO.getCartId(), cartVO.getUserId(), cartVO.getItems().size());
            }
            return ResponseEntity.ok(cartVO);
        } catch (BusinessException e) {
            log.warn("获取购物车失败: error={}", e.getMessage());
            throw e;
        } finally {
            // 结束性能监控
            LogUtil.stopTimer();
            // 清理上下文
            LogUtil.clearContext();
        }
    }


    @Operation(
            summary = "添加商品到购物车",
            description = "将指定服装添加到当前登录用户的购物车中。如果服装已存在，则增加数量。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功，返回更新后的购物车信息"),
            @ApiResponse(responseCode = "400", description = "请求参数无效或服装信息不存在"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "服装不存在或已下架"),
            @ApiResponse(responseCode = "409", description = "库存不足")
    })
    @PostMapping("/items")
    public ResponseEntity<CartVO> addToCart(@Valid @RequestBody AddToCartRequest addRequest) {
        // 设置追踪ID
        LogUtil.setTraceId();

        // 开始性能监控
        LogUtil.startTimer("GET_CART");

        LogUtil.info("CART", "ADD", "添加商品到购物车请求: costumeId={}, quantity={}, rentalDays={}",
                addRequest.getCostumeId(), addRequest.getQuantity(), addRequest.getRentalDays());
        try {
            CartVO cartVO = cartService.addToCart(addRequest);

            LogUtil.info("CART","ADD", "添加商品到购物车成功: costumeId={}, quantity={}, rentalDays={}",
                    addRequest.getCostumeId(), addRequest.getQuantity(), addRequest.getRentalDays());

            return ResponseEntity.ok(cartVO);
        } catch (BusinessException e) {

            LogUtil.warn("CART","ADD",
                    "添加商品到购物车失败: costumeId={}, error={}",
                    addRequest.getCostumeId(), e.getMessage());

            throw e;
        } finally {
            // 结束性能监控
            LogUtil.stopTimer();
            // 清理上下文
            LogUtil.clearContext();
        }
    }


    @Operation(
            summary = "从购物车移除商品",
            description = "从购物车中移除指定的商品。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "移除成功"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "购物车商品不存在")
    })
    @DeleteMapping("/items/{itemId}")
    public ResponseEntity<Void> removeFromCart(@PathVariable Long itemId) {
        log.info("从购物车移除商品请求: itemId={}", itemId);
        try {
            cartService.removeFromCartItem(itemId);
            log.info("从购物车移除商品成功: itemId={}", itemId);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            log.warn("从购物车移除商品失败: itemId={}, error={}", itemId, e.getMessage());
            throw e;
        }
    }
}
